﻿package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;
import cc.ufinity.networkdiagnose.adapter.APListAdapter;
import cc.ufinity.networkdiagnose.adapter.SortButtoniListAdapter;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.ChinaNetAccount;
import cc.ufinity.networkdiagnose.manager.ChinaNetAuthManager;
import cc.ufinity.networkdiagnose.manager.ChinaUnicomAccount;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.RandomGUID;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.manager.Task.GPS;
import cc.ufinity.networkdiagnose.manager.Task.GSM;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.manager.Task.TD;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.UnicomWebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.ComparatorUser;
import cc.ufinity.networkdiagnose.util.GPSUtils;
import cc.ufinity.networkdiagnose.view.R;

public class GeneralTestWidget extends FrameLayout {

    protected final static int TASK_PERFORM_INTERVAL = 1000;
    protected static final String TAG_REFER_TASK = "task";
    protected static final String TAG_REFER_RESULT_FLAG = "resultPage";
    protected static final String TAG_REFER_RESULTTD = "resultTD";
    protected static final String TAG_REFER_RESULTGSM = "resultGSM";
    protected static final String TAG_REFER_RESULTWALN = "resultWLAN";
    protected static final String TAG_REFER_RESULTALL = "resultAll";
    protected static final String TAG_REFER_RESULTTD2 = "resultTestTD";
    protected static final String TAG_REFER_RESULTGSM2 = "resultTestGSM";
    protected static final String TAG_REFER_RESULTWALN2 = "resultTestWLAN";
    protected static final String TAG_REFER_RESULTALL2 = "resultTestAll";
    protected static final String TAG_CAMERA_TASK="cameratask";
    protected static final String TAG_CAMERA_FLAG="cameraflag";
//	protected static final String TASK_BEGIN_FLAG = "taskBeginFlag";
//	protected static final String TEST_BEGIN_FLAG = "testBeginFlag";
//	protected static final String TASK_BEGIN_YES = "yes";
//	protected static final String TASK_BEGIN_NO = "no";
    protected static final String TAG_CAMERA_FLAG_VALUE="camera_result";
    protected static final int TOAST_MSG_DISPLAY_TIME = 15000;// 定义消息显示时间，默认8秒
    
    protected static String testWidget;

    protected boolean executable = true;
    protected ProgressDialog progressDialog;
    protected ProgressDialog messageDialog;
    protected AlertDialog wifiListDialog;
    protected WlanManager wManager;
    protected ScanResult selectedScanResult;
    private Activity ctx;
    
    public static Toast toast;
    private DBManager db; 
    public static ChinaNetAuthManager chinaNetAuthManager ;
    public static UnicomWebAuthManager unicomAuthManager;
    
    private  String[] l  ;
    public GeneralTestWidget(Activity context) {
        super(context);
        this.ctx = context;
        
        chinaNetAuthManager = new ChinaNetAuthManager(ctx);
        unicomAuthManager = new UnicomWebAuthManager();
        GlobalApp.chinaNetAuthManager = chinaNetAuthManager;
        GlobalApp.unicomAuthManager = unicomAuthManager;
        
        toast = Toast.makeText(ctx, "", Toast.LENGTH_LONG);
        
        if (this instanceof TaskWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_FLAG_NAME, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_FLAG_NAME, 0);
        }
        /*if (this instanceof CheckWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_FLAG_NAME_CHECK, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_FLAG_NAME_CHECK, 0);
        } */
        if (this instanceof TaskResult) {
            context.getIntent().putExtra(MessageWhat.INDEX_TASK_RESULT, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TASK_RESULT, 0);
        }
        if (this instanceof TaskResultTD) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultTD_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultTD_WIDGET, 0);
        }
        if (this instanceof TaskResultGSM) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultGSM_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultGSM_WIDGET, 0);
        }
        if (this instanceof TaskResultWlan) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultWlan_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultWlan_WIDGET, 0);
        }
        if (this instanceof TaskResultAll) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultAll_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultAll_WIDGET, 0);
        }
//
        if (this instanceof TaskTestResultTD) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultTD_WIDGET2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultTD_WIDGET2, 0);
        }
        if (this instanceof TaskTestResultGSM) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultGSM_WIDGET2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultGSM_WIDGET2, 0);
        }
        if (this instanceof TaskTestResultWlan) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultWlan_WIDGET2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultWlan_WIDGET2, 0);
        }
        if (this instanceof TaskTestResultAll) {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultAll_WIDGET2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TaskResultAll_WIDGET2, 0);
        }
        //
       /* if (this instanceof TestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_TEST_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TEST_WIDGET, 0);
        }  */
        if (this instanceof MoveOrOther) {
            context.getIntent().putExtra(MessageWhat.INDEX_MOVEOROTHER_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_MOVEOROTHER_WIDGET, 0);
        } 
        if (this instanceof OtherNet) {
            context.getIntent().putExtra(MessageWhat.INDEX_OTHERNET_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_OTHERNET_WIDGET, 0);
        } 
        if (this instanceof SelectNetType_main) {
        	System.out.println("【 0 】");
            context.getIntent().putExtra(MessageWhat.INDEX_SelectNetType_main_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_SelectNetType_main_WIDGET, 0);
        }
        if (this instanceof TestWidget_TD) {
            context.getIntent().putExtra(MessageWhat.INDEX_TestWidget_TD_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TestWidget_TD_WIDGET, 0);
        }
        if (this instanceof TestWidget_GSM) {
            context.getIntent().putExtra(MessageWhat.INDEX_TestWidget_GSM_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TestWidget_GSM_WIDGET, 0);
        }
        if (this instanceof TestWidget_Wlan) {
            context.getIntent().putExtra(MessageWhat.INDEX_TestWidget_Wlan_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TestWidget_Wlan_WIDGET, 0);
        }
        if (this instanceof RssiWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_RssiWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_RssiWidget_WIDGET, 0);
        }
        if (this instanceof PingWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_PingWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_PingWidget_WIDGET, 0);
        }
        if (this instanceof FtpTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_FtpTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_FtpTestWidget_WIDGET, 0);
        }
        if (this instanceof HttpTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_HttpTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_HttpTestWidget_WIDGET, 0);
        }
        
        if (this instanceof ApRelevanceTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_ApRelevanceTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_ApRelevanceTestWidget_WIDGET, 0);
        }
        if (this instanceof SegregateTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_SegregateTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_SegregateTestWidget_WIDGET, 0);
        }
        if (this instanceof RoamTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_RoamTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_RoamTestWidget_WIDGET, 0);
        }
        if (this instanceof WebauthTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_WebauthTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_WebauthTestWidget_WIDGET, 0);
        }
        if (this instanceof PeapWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_PeapWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_PeapWidget_WIDGET, 0);
        }
        
        if (this instanceof WifiSnrTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_WifiSnrTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_WifiSnrTestWidget_WIDGET, 0);
        }
        if (this instanceof TD_GSM_WifiSnrTestWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_TD_GSM_WifiSnrTestWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TD_GSM_WifiSnrTestWidget_WIDGET, 0);
        }
        if (this instanceof TD_GSM_RssiWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_TD_GSM_RssiWidget_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_TD_GSM_RssiWidget_WIDGET, 0);
        }
        if (this instanceof Test_Task_Widget_Wlan) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan_WIDGET, 1);
            System.out.println("============     Test_Task_Widget_Wlan     ==============");
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan_WIDGET, 0);
        }
        if (this instanceof Test_Task_Widget_Wlan2) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan2_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan2_WIDGET, 0);
        }
        if (this instanceof Test_Task_Widget_TD) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_TD_WIDGET, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_TD_WIDGET, 0);
        }
        //
        if (this instanceof TaskTestWlanWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan_WIDGET2, 1);
            System.out.println("============     Test_Task_Widget_Wlan     ==============");
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan_WIDGET2, 0);
        }
        if (this instanceof TaskTestWlan2Widget) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan2_WIDGET2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan2_WIDGET2, 0);
        }
        if (this instanceof TaskTestTDWidget) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_TD_WIDGET2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_TD_WIDGET2, 0);
        }
        if (this instanceof Test_Task_Widget_Other) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Other, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Other, 0);
        }
        if (this instanceof Test_Task_Widget_Other2) {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Other2, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Other2, 0);
        }
        
        if (this instanceof CameraWidget) {
            context.getIntent().putExtra(MessageWhat.CameraWidget, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.CameraWidget, 0);
        }
        if (this instanceof FtpDownloadWidget) {
            context.getIntent().putExtra(MessageWhat.LFTPDOWNLOAD, 1);
        } else {
            context.getIntent().putExtra(MessageWhat.LFTPDOWNLOAD, 0);
        } //1-16 svenke
        //
        wManager = new WlanManager(ctx);  
    }
    protected FTPConfig getFTPConfig(Activity ctx) {
    	try { 
        		DBManager db = new DBManager(ctx);
//    	        FTPConfig ftp = db.getFtp2();
//    	        if(ftp!=null)
//    	        {
//    	        	db.saveFtp(ftp);
//    	        	db.release();
//    	        }else {
        		FTPConfig ftp = db.getFtp();
//				}
    	        db.release();
    	        if (ftp == null) {
    	        //    showMessage(ctx, "获取FTP账号失败，请检查FTP配置是否正确.");
    	            return new FTPConfig();
    	        } else {
    	            return ftp;
    	        }
		} catch (Exception e) {
			// TODO: handle exception 
			e.printStackTrace();
        	return new FTPConfig();
		} 
    }

    public void sendMsg(int what, Handler handler) {
        if (null != handler) {
            Message msg = handler.obtainMessage();
            msg.what = what;
            msg.sendToTarget();
        }
    }

    protected void showWifiListDialog00(Activity ctx, WlanManager wlanManager, final Handler handler) {
        final List<ScanResult> scanResults = wlanManager.getScanResults();
        String[] apList = createWifiTitles(scanResults);
        final List<ScanResult> scanResultTemp = selectCMCC(scanResults);
        scanResultTemp.addAll(selectCMCCAuto(scanResults));
        scanResultTemp.addAll(selectCMCCEdu(scanResults));
        scanResultTemp.addAll(selectOther(scanResults));
        AlertDialog.Builder ad = new AlertDialog.Builder(ctx);
        ad.setTitle("Wifi列表");
        ad.setSingleChoiceItems(apList, 0, new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                selectedScanResult = scanResultTemp.get(which);
                System.out.println(selectedScanResult.SSID+"===========================选择"+selectedScanResult.BSSID);
                Message msg = new Message();
                msg.what = MessageWhat.WIFI_SELECTED;
                handler.sendMessage(msg);
                wifiListDialog.dismiss();
            }
        });
        wifiListDialog = ad.create();
        wifiListDialog.show();
    }
    
protected void showWifiListDialog(final Activity ctx, WlanManager wlanManager, final Handler handler) {
		
		final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
	    waitDialog.setContentView(R.layout.wifi_list_dialog);
	    waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
	//     waitDialog.setCancelable(false);
	    
	    //设置窗口里控件的透明度
	    Window window = waitDialog.getWindow();
	    WindowManager.LayoutParams wl = window.getAttributes();
	    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
	    wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
	    window.setAttributes(wl);
	
	    final Activity activity = ctx;
	    List<ScanResult> scanResults = wlanManager.getScanResults();
       /* final List<ScanResult> scanResultTemp = selectCMCC(scanResults);
        scanResultTemp.addAll(selectCMCCAuto(scanResults));
        scanResultTemp.addAll(selectCMCCEdu(scanResults));
        scanResultTemp.addAll(selectOther(scanResults));
        scanResultTemp.addAll(selectOther2(scanResults));*/

        if(!GlobalApp.DEBUG && !"ApRelevanceTestWidget".equals(testWidget) ) {
        	scanResults = selectCMCC(scanResults);
        }
        
        final List<ScanResult> scanResultTemp = scanResults;
        	
	    Collections.sort(scanResultTemp, new APcompare(LEVEL));
	    
	    final Button bt_sort = (Button)waitDialog.findViewById(R.id.wifi_list_sort);
	    bt_sort.setVisibility(Button.GONE);
	    final APListAdapter apListAdapter = new APListAdapter(activity, scanResultTemp);
	    final ListView listView = (ListView)waitDialog.findViewById(R.id.wifi_list_dialog_sort);
	
		listView.setOnItemClickListener(new OnItemClickListener() {
	
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
				selectedScanResult = scanResultTemp.get(arg2);
				System.out.println(selectedScanResult.SSID+"===========================选择"+selectedScanResult.BSSID);
                Message msg = new Message();
                msg.what = MessageWhat.WIFI_SELECTED;
                handler.sendMessage(msg);
	
	        	waitDialog.dismiss();
				
			}
		});
	    listView.setAdapter(apListAdapter);
		
	    waitDialog.show(); 
	}
    
    private void showSortButton(final Handler handler) {
    	final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
        waitDialog.setContentView(R.layout.wifi_list_sort_button);
        waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent2);
        
      //设置窗口里控件的透明度
        Window window = waitDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        /*lp.x = 260; // 新位置X坐标 
        lp.y = 155; // 新位置Y坐标 
*/
        WindowManager m = ctx.getWindowManager(); 
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用 
        lp.x = (int) (d.getWidth() * 0.542); // 新位置X坐标 480
        lp.y = (int) (d.getHeight() * 0.194); // 新位置Y坐标 800
        //System.out.println("d.getHeight() :　d.getWidth()　＝　" + d.getHeight() + " : " + d.getWidth());
        lp.alpha = 0.9f; // 透明度 
        window.setAttributes(lp); 

        LinearLayout linearLayout = (LinearLayout)waitDialog.findViewById(R.id.linearlayout_bt_sort_list);
        final ListView listView = (ListView)waitDialog.findViewById(R.id.bt_sort_list);
        List<String> list_buttons = new ArrayList<String>();
        String name = "默    认";
        list_buttons.add(name);
        name = "S S I D";
        list_buttons.add(name);
        name = "MAC地址";
        list_buttons.add(name);
        name = "信号强度";
        list_buttons.add(name);
        name = "信    道";
        list_buttons.add(name);
        
        SortButtoniListAdapter adapter = new SortButtoniListAdapter(ctx, list_buttons);
        listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Message msg = handler.obtainMessage();
				msg.arg1 = arg2 + 1;
				msg.sendToTarget();
				waitDialog.dismiss();
			}
		});
        listView.setAdapter(adapter);
        waitDialog.setCancelable(true);
        waitDialog.setCanceledOnTouchOutside(true);
        waitDialog.show();
        
        final long duration = 200;
        AnimationSet animation = new AnimationSet(true);
      //移动变化
    	TranslateAnimation myAnimation_Translate;
    	myAnimation_Translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, 
				   Animation.RELATIVE_TO_SELF, 0.0f, 
				   Animation.RELATIVE_TO_SELF, -1.0f, 
				   Animation.RELATIVE_TO_SELF, 0.0f);
    	myAnimation_Translate.setDuration(duration);
    	
    	animation.addAnimation(myAnimation_Translate);
    	//animation.addAnimation(myAnimation_Rotate);
    	animation.setFillEnabled(true);
    	animation.setFillAfter(true);
    	animation.setInterpolator(AnimationUtils.loadInterpolator(ctx, android.R.anim.accelerate_interpolator));
    	linearLayout.startAnimation(animation);
    }
    
    
protected void showOneKeyWifiListDialog(final Activity ctx, WlanManager wlanManager, final Handler handler) {
    	
    	final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
        waitDialog.setContentView(R.layout.wifi_list_dialog);
        waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
   //     waitDialog.setCancelable(false);
        
        //设置窗口里控件的透明度
        Window window = waitDialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
        window.setAttributes(wl);

        final Activity activity = ctx;
        final List<ScanResult> scanResults = wlanManager.getScanResults();
        final List<ScanResult> scanResultTemp = new ArrayList<ScanResult>();
        final List<ScanResult> list_CMCC = selectCMCC(scanResults);  
        final List<ScanResult> list_CMCCAuto = selectCMCCAuto(scanResults);
        final List<ScanResult> list_CMCCEdu = selectCMCCEdu(scanResults);
        final List<ScanResult> list_Other = selectOther(scanResults);
        final List<ScanResult> list_Other2 = selectOther2(scanResults);
        
        Collections.sort(list_CMCC, new APcompare(LEVEL));
        Collections.sort(list_CMCCAuto, new APcompare(LEVEL));
        Collections.sort(list_CMCCEdu, new APcompare(LEVEL));
//        Collections.sort(list_Other2, new APcompare(LEVEL));
        
        scanResultTemp.addAll(list_CMCC);
        //scanResultTemp.addAll(list_CMCCAuto);
        //scanResultTemp.addAll(list_CMCCEdu);
//        scanResultTemp.addAll(list_Other2);
        
        if(GlobalApp.DEBUG) {
        	Collections.sort(list_Other, new APcompare(LEVEL));
        	scanResultTemp.addAll(list_Other);
        }
        
        final APListAdapter apListAdapter = new APListAdapter(activity, scanResultTemp);
        final ListView listView = (ListView)waitDialog.findViewById(R.id.wifi_list_dialog_sort); 

        final Handler hand = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch(msg.arg1) {
				case 1:
					scanResultTemp.clear();
					
					scanResultTemp.addAll(list_CMCC);
			        //scanResultTemp.addAll(list_CMCCAuto);
			        //scanResultTemp.addAll(list_CMCCEdu);
			        if(GlobalApp.DEBUG) {
			        	scanResultTemp.addAll(list_Other);
			        }
//			        scanResultTemp.addAll(list_Other2);
			        
			        apListAdapter.notifyDataSetChanged();
					break;
				case 2:
					Collections.sort(scanResultTemp, new APcompare(SSID));
			        
			        apListAdapter.notifyDataSetChanged();
					break;
				case 3:
					Collections.sort(scanResultTemp, new APcompare(MAC));
			        
			        apListAdapter.notifyDataSetChanged();
					break;
				case 4:
					Collections.sort(scanResultTemp, new APcompare(LEVEL));
			        
			        apListAdapter.notifyDataSetChanged();
					break;
				case 5:
					Collections.sort(scanResultTemp, new APcompare(CHANNLE));
			        
			        apListAdapter.notifyDataSetChanged();
					break;
				}

				super.handleMessage(msg);
			}
        	
        };
        
        final Button bt_sort = (Button)waitDialog.findViewById(R.id.wifi_list_sort);
        bt_sort.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showSortButton(hand);
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				GlobalApp.taskOtherList.clear();
				GlobalApp.index = 0;
				
				selectedScanResult = scanResultTemp.get(arg2);
                //Task task = new Task();
                Task task = GlobalApp.taskWlan;
                task.scanResult = selectedScanResult;
                task.mac = selectedScanResult.BSSID;

                activity.getIntent().putExtra(TAG_REFER_TASK, task);
                activity.getIntent().putExtra("from", "TestWidget");

				task.taskType = "网络测试";
				WlanManager wlanManager = new WlanManager(activity);
				wlanManager.setMobileDataEnabled(activity,false);
				task.selNetType = ConnectivityManager.TYPE_WIFI;
				activity.getIntent().putExtra(TAG_REFER_TASK, task); 
				Test_Task_Widget_Wlan ttw2 = new Test_Task_Widget_Wlan(activity);
				activity.setContentView(ttw2);

				DBManager db = new DBManager(ctx);
				ChinaNetAccount  china = db.getChinaNetAccount();
				ChinaUnicomAccount unicom = db.getUnicomAccount();
				db.release();
				if(list_Other2.size() > 0) {
            		Task t;
            		if(china != null && china.userName != null && china.userName.length()>10) {
            			for(ScanResult scanResult:list_Other2) {
	            			if(scanResult.SSID.equals(WlanManager.SSID_ChinaNet) && scanResult.level >= -70) {
	            				t = new Task();
	                    		t.scanResult = scanResult;
	                    		t.mac = scanResult.BSSID;
	                    		
	                    		initTask(t, task.id);
	                    		
	                    		GlobalApp.taskOtherList.add(t);
	            			}
	                	}
            		} 
            		if(unicom != null && unicom.userName != null && unicom.userName.length()>10) {
            			for(ScanResult scanResult:list_Other2) {
	            			if((scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom1) || scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom2))
	            					&& scanResult.level >= -70) {
	            				t = new Task();
	                    		t.scanResult = scanResult;
	                    		t.mac = scanResult.BSSID;
	                    		
	                    		initTask(t, task.id);
	                    		
	                    		GlobalApp.taskOtherList.add(t);
	            			}
	                	}
            		}
            		
            	}
            	
            	if(GlobalApp.DEBUG) {
            		if(china != null && china.userName != null && china.userName.length()>10) {
            			Task t;
                    	for(int i=1; i<=3; i++) {
        	        		t = new Task();
        	        		ScanResult scanResult = selectedScanResult;
        	        		t.scanResult = scanResult;
        	        		t.mac = scanResult.BSSID;
        	        		
        	        		initTask(t, task.id);
        	        		
        	        		GlobalApp.taskOtherList.add(t);
                		}
            		}
            		
            	}

            	waitDialog.dismiss();
				
			}
		});
        listView.setAdapter(apListAdapter);
		
        waitDialog.show(); 
    }

	private void initTask(Task task, String randomTaskId) {
        SharedPreferences settings;
        String urlString;
        HttpTask httpTask;
        List<HttpTask> httpTasks;
        FTPConfig ftpConfig;
        String ftpString;
        FTPTask ftpTask;
        List<FTPTask> ftpTasks;
        PingTask pingTask;
        List<PingTask> pingTasks;
        String number;

         task.id = randomTaskId;
         settings = ctx.getSharedPreferences(HttpConfigWidget.PREFS_HTTP_NAME, 0);
         urlString = settings.getString(HttpConfigWidget.PREFS_HTTP_KEY, "");
         urlString = (urlString ==null||urlString.equals(""))?"www.baidu.com":urlString;
         httpTask = task.newHttpTask(urlString);
         httpTasks = new ArrayList<Task.HttpTask>();
         httpTasks.add(httpTask);
         task.httpTasks = httpTasks; 

         ftpConfig = getFTPConfig(ctx);
         ftpString =ftpConfig==null?"": ftpConfig.address+","+ftpConfig.userName+","+ftpConfig.password;
         ftpTask = task.newFTPTask(ftpString);
         ftpTasks = new ArrayList<Task.FTPTask>();
         ftpTasks.add(ftpTask);
         task.ftpTasks = ftpTasks;   

         pingTask = task.newPingTask("www.baidu.com");
         pingTasks = new ArrayList<Task.PingTask>();
         pingTasks.add(pingTask);
         task.pingTasks = pingTasks; 
         settings = ctx.getSharedPreferences(PingConfigWidget.PREFS_PING_NAME, 0);
         number = settings.getString(PingConfigWidget.PREFS_PING_KEY, "4");
         number = (number==null || number.equals(""))?"4":number;
         task.testCount = Integer.parseInt(number);
         task.taskType = "网络测试";
         task.testType = 1;
         task.selNetType = ConnectivityManager.TYPE_WIFI;
	}

	protected void showOtherWifiListDialog(final Activity ctx, WlanManager wlanManager, final Handler handler) {
		
		final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
	    waitDialog.setContentView(R.layout.wifi_list_dialog);
	    waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
	//     waitDialog.setCancelable(false);
	    
	    //设置窗口里控件的透明度
	    Window window = waitDialog.getWindow();
	    WindowManager.LayoutParams wl = window.getAttributes();
	    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
	    wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
	    window.setAttributes(wl);
	
	    final Activity activity = ctx;
	    List<ScanResult> scanResults = wlanManager.getScanResults();

	    if(GlobalApp.DEBUG) {
	    	scanResults = wlanManager.getScanResults();
	    } else {
	    	scanResults = selectOther2(wlanManager.getScanResults());
	    }
	    
	    final List<ScanResult> list_Other = scanResults;
	    Collections.sort(list_Other, new APcompare(LEVEL));
	    
	    final Button bt_sort = (Button)waitDialog.findViewById(R.id.wifi_list_sort);
	    bt_sort.setVisibility(Button.GONE);
	    final APListAdapter apListAdapter = new APListAdapter(activity, list_Other);
	    final ListView listView = (ListView)waitDialog.findViewById(R.id.wifi_list_dialog_sort);
	
		listView.setOnItemClickListener(new OnItemClickListener() {
	
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
				selectedScanResult = list_Other.get(arg2);
				Task task = GlobalApp.taskOther;

				String randomTaskId = (new RandomGUID()).valueAfterMD5;
		        SharedPreferences settings;
		        String urlString;
		        HttpTask httpTask;
		        List<HttpTask> httpTasks;
		        FTPConfig ftpConfig;
		        String ftpString;
		        FTPTask ftpTask;
		        List<FTPTask> ftpTasks;
		        PingTask pingTask;
		        List<PingTask> pingTasks;
		        String number;
		        
		         task.id = randomTaskId;
		         settings = ctx.getSharedPreferences(HttpConfigWidget.PREFS_HTTP_NAME, 0);
		         urlString = settings.getString(HttpConfigWidget.PREFS_HTTP_KEY, "");
		         urlString = (urlString ==null||urlString.equals(""))?"www.baidu.com":urlString;
		         httpTask = task.newHttpTask(urlString);
		         httpTasks = new ArrayList<Task.HttpTask>();
		         httpTasks.add(httpTask);
		         task.httpTasks = httpTasks; 

		         ftpConfig = getFTPConfig(ctx);
		         ftpString =ftpConfig==null?"": ftpConfig.address+","+ftpConfig.userName+","+ftpConfig.password;
		         ftpTask = task.newFTPTask(ftpString);
		         ftpTasks = new ArrayList<Task.FTPTask>();
		         ftpTasks.add(ftpTask);
		         task.ftpTasks = ftpTasks;   

		         pingTask = task.newPingTask("www.baidu.com");
		         pingTasks = new ArrayList<Task.PingTask>();
		         pingTasks.add(pingTask);
		         task.pingTasks = pingTasks; 
		         settings = ctx.getSharedPreferences(PingConfigWidget.PREFS_PING_NAME, 0);
		         number = settings.getString(PingConfigWidget.PREFS_PING_KEY, "4");
		         number = (number==null || number.equals(""))?"4":number;
		         task.testCount = Integer.parseInt(number);
		         task.taskType = "网络测试";
		         task.testType = 1;
		         task.selNetType = ConnectivityManager.TYPE_WIFI;
				
	            task.scanResult = selectedScanResult;
	            task.mac = selectedScanResult.BSSID;
	            
        		WlanManager wlanManager = new WlanManager(activity);
                wlanManager.setMobileDataEnabled(activity,false);
                
                activity.getIntent().putExtra("from", "TestWidget");
 	            activity.getIntent().putExtra(TAG_REFER_TASK, task); 
 	            Test_Task_Widget_Other ttwo = new Test_Task_Widget_Other(activity);
 	            activity.setContentView(ttwo);
	
	        	waitDialog.dismiss();
				
			}
		});
	    listView.setAdapter(apListAdapter);
		
	    waitDialog.show(); 
	}

    private final static int SSID = 1;
	private final static int MAC = 2;
	private final static int LEVEL = 3;
	private final static int CHANNLE = 4;
	final class APcompare implements Comparator<ScanResult> {

		private int flag;
		public APcompare(int flag) {
			this.flag = flag;
		}
		@Override
		public int compare(ScanResult p1, ScanResult p2) {
			// TODO Auto-generated method stub
			
            if(flag == SSID) {
            	return (p1.SSID).compareToIgnoreCase(p2.SSID);
            } else if(flag == MAC) {
            	return (p1.BSSID).compareToIgnoreCase(p2.BSSID);
            } else if(flag == LEVEL) {
            	if((p1.level) > (p2.level)) {
            		return -1;
            	} else if((p1.level) == (p2.level)) {
            		return 0;
            	} else {
            		return 1;
            	}
            } else if(flag == CHANNLE) {
            	if((p1.frequency) > (p2.frequency)) {
            		return 1;
            	} else if((p1.frequency) == (p2.frequency)) {
            		return 0;
            	} else {
            		return -1;
            	}
            }
			
            return 0;

		}
		
	}
    
    protected void showMessageDialog(Activity ctx, final String text) {
    	messageDialog = new ProgressDialog(ctx);
        messageDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        messageDialog.setTitle("请稍等");
//        messageDialog.setIcon(R.drawable.smile);
        messageDialog.setMessage(text);
        messageDialog.setCancelable(false);
        messageDialog.setOnKeyListener(new android.content.DialogInterface.OnKeyListener(){
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (KeyEvent.KEYCODE_BACK == keyCode) {
					if(messageDialog != null) {
						messageDialog.dismiss();
					}
				}
				return false;
			}
        });
        messageDialog.show();
    }

    protected void dismissMessageDialog() {
    	try{
	        messageDialog.dismiss();
    	}catch(Exception e){
    	}
    }


    protected void showProgressDialog(Activity ctx, final String text, final int max) {
        progressDialog = new ProgressDialog(ctx);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("请稍等");
//      progressDialog.setIcon(R.drawable.smile);
        progressDialog.setMessage(text);
        progressDialog.setProgress(0);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(max);
        progressDialog.setCancelable(false);
        progressDialog.setOnKeyListener(new android.content.DialogInterface.OnKeyListener(){
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (KeyEvent.KEYCODE_BACK == keyCode) {
					progressDialog.dismiss();
				}
				return false;
			}
        });
        progressDialog.show();
    }

    protected void setDialogProgressMessage(String message) {
    	if (progressDialog != null)
            progressDialog.setMessage(message);
    }
    protected void setDialogProgress(int value) {
        if (progressDialog != null)
            progressDialog.setProgress(value);
    }

    protected void dismissProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    protected void showMessage(Context ctx, String msg) {
    	
    	toast.setText(msg);
    	toast.show();
       // Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }
    
    protected void handlerSendToTarget(Handler handler, int message) {
		Message msg = handler.obtainMessage();
		msg.arg1 = message;
		msg.sendToTarget();
	}

   /* protected void back(Activity context) {
    	executable = false;
    	TestWidget tw = new TestWidget(context); 
        context.setContentView(tw);
    }*/
    
    /**
     * 结果展示界面的返回按钮事件响应
     */
    protected void back_button() {
    	if(GlobalApp.is_NET_TEST) {
    		backToMain(ctx);
    	} else if(GlobalApp.is_TASK_TEST) {
    		backToTask(ctx);
    	}/* else if(GlobalApp.is_CHECK_TEST) {
    		backToCheck(ctx);
    	}*/
    }
    protected void backToMain(Activity context) {
    	SelectNetType_main sntm = new SelectNetType_main(context); 
        context.setContentView(sntm);
    }

    protected void backToTask(Activity context) {
    	executable = false;
        TaskWidget tw = new TaskWidget(context);
        context.setContentView(tw);
        tw.start();
    }
    
   /* protected void backToCheck(Activity context) {
    	executable = false;
    	CheckWidget cw = new CheckWidget(context); 
    	context.setContentView(cw);
		cw.start();
    }*/
    
    protected void backToTestWidget_Wlan(Activity context) { 
    	executable = false;
        context.setContentView(new TestWidget_Wlan(context));
    }
    
    protected void backToTestWidget_TD(Activity context) { 
        context.setContentView(new TestWidget_TD(context));
    }
    
    protected void backToTestWidget_GSM(Activity context) { 
        context.setContentView(new TestWidget_GSM(context));
    }

    protected void backToConfig(Activity context) {
        SettingWidget tw = new SettingWidget(context);
        context.setContentView(tw);
    }

    protected void setScrollViewDown(final ScrollView svResult) {
        svResult.post(new Runnable() {
            public void run() {
                svResult.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }
    
    protected int getMax(final double[] d) {
    	int i = 0;
    	for(double dd:d) {
    		if(i < dd) {
    			i = (int)dd + 1;
    		}
    	}
    	return i;
    }

	private String[] createWifiTitles(final List<ScanResult> scanResults) {
		l = new String[scanResults.size()];
		ComparatorUser compart=new ComparatorUser();
    	List<ScanResult> scanCMMCC=selectCMCC(scanResults);
    	Collections.sort(scanCMMCC,compart);
    	int num=0;
    	 for (int i = 0; i < scanCMMCC.size(); i++) {
             ScanResult obj = scanCMMCC.get(i);
             StringBuffer sb = new StringBuffer();
             sb.append("SSID: ").append(obj.SSID).append('\n');
             sb.append("Mac : ").append(obj.BSSID).append('\n');
             sb.append("信号强度: ").append(obj.level).append("\n")
             .append("Chanel: ").append(getFrequency(obj.frequency)).append('\n');
             l[num] = sb.toString();
             num++;
         }
    	List<ScanResult> scanCMCCAuto=selectCMCCAuto(scanResults);	
    	Collections.sort(scanCMCCAuto,compart);
    	for (int i = 0; i < scanCMCCAuto.size(); i++) {
            ScanResult obj = scanCMCCAuto.get(i);
            StringBuffer sb = new StringBuffer();
            sb.append("SSID: ").append(obj.SSID).append('\n');
            sb.append("Mac : ").append(obj.BSSID).append('\n');
            sb.append("信号强度: ").append(obj.level).append("\n")
            .append("Chanel: ").append(getFrequency(obj.frequency)).append('\n');
             l[num] = sb.toString();
             num++;
        }
    	List<ScanResult> scanCMCCEDU=selectCMCCEdu(scanResults);
    	Collections.sort(scanCMCCEDU,compart);
      	 for (int i = 0; i < scanCMCCEDU.size(); i++) {
               ScanResult obj = scanCMCCEDU.get(i);
               StringBuffer sb = new StringBuffer();
               sb.append("SSID: ").append(obj.SSID).append('\n');
               sb.append("Mac : ").append(obj.BSSID).append('\n');
               sb.append("信号强度: ").append(obj.level).append("\n")
               .append("Chanel: ").append(getFrequency(obj.frequency)).append('\n');
               l[num] = sb.toString();
               num++;
           }
      	 List<ScanResult> Other=selectOther(scanResults);
      /*	scanResults.removeAll(scanCMCCEDU);
    	scanResults.removeAll(scanCMMCC);
    	scanResults.removeAll(scanCMCCAuto);*/
    	Collections.sort(Other,compart);
    	 for (int i=0;i<scanResults.size();i++){  
    		 ScanResult user_temp=(ScanResult)scanResults.get(i);    
    		 System.out.println(user_temp.level+","+user_temp.SSID);
    		 }
        int length = Other.size();
        for (int i = 0; i < length; i++) {
            ScanResult obj = Other.get(i);
            StringBuffer sb = new StringBuffer();
            sb.append("SSID: ").append(obj.SSID).append('\n');
            sb.append("Mac : ").append(obj.BSSID).append('\n');
            sb.append("信号强度: ").append(obj.level).append("\n")
            .append("Chanel: ").append(getFrequency(obj.frequency)).append('\n');
            l[num] = sb.toString();
            num++;
        }
        num=0;
		return l;
    }
	
	//信道的转换
	public int getFrequency(int a){
		int channel=1;
		 if(a==2412){
			 channel=1;
		}else if(a==2417){
			 channel=2;
		}else if(a==2422){
			 channel=3;
		}else if(a==2427){
			 channel=4;
		}else if(a==2432){
			 channel=5;
		}else if(a==2437){
			 channel=6;
		}else if(a==2442){
			 channel=7;
		}else if(a==2447){
			 channel=8;
		}else if(a==2452){
			 channel=9;
		}else if(a==2457){
			 channel=10;
		}else if(a==2462){
			 channel=11;
		}else if(a==2467){
			 channel=12;
		}else if(a==2472){
			 channel=13;
		}else if(a==2484){
			 channel=14;
		}
	 return channel;
	}

	
	 /**
     * 筛选电信和联通的AP
     * @param scanResults
     * @return
     */
    public List<ScanResult> selectOther2(final List<ScanResult> scanResults){
    	List<ScanResult> list = new ArrayList<ScanResult>();
    	ScanResult scan;
    	if(scanResults!=null){
    		 for(int i=0;i<scanResults.size();i++){
        		 scan=scanResults.get(i);
        		 if(scan!=null && scan.SSID!=null 
        				 && (scan.SSID.equals(WlanManager.SSID_ChinaNet)
        				    ||scan.SSID.equals(WlanManager.SSID_ChinaUnicom1)
        				    ||scan.SSID.equals(WlanManager.SSID_ChinaUnicom2))
        				 && scan.level > -70 ){
        			 list.add(scan);
        		 }
        	 }
    	}
    	return list;
    }
    
    /**
     *这个方法是行扫描结果里面选择CMCC的AP，选择之后去掉这些AP
     * @param scanResults
     * @return
     */
    private List<ScanResult> selectOther(final List<ScanResult> scanResults){
    	List<ScanResult> scanCMCC=new ArrayList<ScanResult>();
    	ScanResult scan;
    	if(scanResults!=null){
    		 for(int i=0;i<scanResults.size();i++){
        		 scan=scanResults.get(i);
        		 if(scan!=null && scan.SSID!=null 
        				 &&(scan.SSID.equals(WlanManager.SSID_CMCC)
        				    ||scan.SSID.equals(WlanManager.SSID_CMCC_AUTO)
        				    ||scan.SSID.equals(WlanManager.SSID_CMCC_EDU)
        				    ||scan.SSID.equals(WlanManager.SSID_ChinaNet)
        				    ||scan.SSID.equals(WlanManager.SSID_ChinaUnicom1)
        				    ||scan.SSID.equals(WlanManager.SSID_ChinaUnicom2))){
        		 } else {
        			 scanCMCC.add(scan);
        		 }
        	 }
    	}
    	return scanCMCC;
    }
	
   
    /**
     *这个方法是行扫描结果里面选择CMCC的AP，选择之后去掉这些AP
     * @param scanResults
     * @return
     */
    private List<ScanResult> selectCMCC(final List<ScanResult> scanResults){
    	List<ScanResult> scanCMCC = new ArrayList<ScanResult>();
    	ScanResult scan;
    	if(scanResults!= null){
    		 for(int i=0;i<scanResults.size();i++){
        		 scan=scanResults.get(i);
        		 if(scan!=null && scan.SSID!=null && (scan.SSID.equals(WlanManager.SSID_CMCC)||scan.SSID.equals(WlanManager.SSID_CMCC_EDU))){
        			 scanCMCC.add(scan);
        		 }
        	 }
    	}
    	return scanCMCC;
    }
    
    /**
     * 这个方法是从扫描的结果里面选择CMCC——Auto的AP，选择之后去掉这些AP
     * @param scanResults
     * @return
     */
    protected List<ScanResult> selectCMCCAuto(final List<ScanResult> scanResults){
    	List<ScanResult> scanCMCCAuto=new ArrayList<ScanResult>();
    	ScanResult scan;
    	if(scanResults!=null){
    		for(int i=0;i<scanResults.size();i++){
	       		 scan=scanResults.get(i);
	       		 if(scan!=null && scan.SSID!=null &&scan.SSID.equals(WlanManager.SSID_CMCC_AUTO)){
	       			 scanCMCCAuto.add(scan);
	       		 }
       	 	}
    	}
    	Collections.sort(scanCMCCAuto, new APcompare(LEVEL));
    	return scanCMCCAuto;
    }
    
   /**
    * 这个方法是为了从扫描结果里面选择CMCC-EDU的AP,选择之后去掉这些AP
    * 
    */
    private List<ScanResult> selectCMCCEdu(final List<ScanResult> scanResults){
    	List<ScanResult> scanCMCCEDU=new ArrayList<ScanResult>();
    	ScanResult scan;
    	if(scanResults!=null){
    		for(int i=0;i<scanResults.size();i++){
	       		 scan=scanResults.get(i);
	       		 if(scan!=null && scan.SSID!=null && scan.SSID.equals(WlanManager.SSID_CMCC_EDU)){
	       			 scanCMCCEDU.add(scan);
	       		 }
       	 	}
    	}
    	return scanCMCCEDU;
    }
    
   
    
    protected boolean uplod(final String fileName, Activity ctx, Handler handler) {
        Message msg = null;
        boolean success = false;
        DBManager db = new DBManager(ctx);
        FTPConfig ftp = db.getFtp2();
        db.release();
        if (ftp == null) {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
            msg.sendToTarget();
            return success;
        }
      //  String localPath = Environment.getExternalStorageDirectory() + "/wlantest/";
      //----------------------  begin ------------------------------------------------- 
        File fileDir = ctx.getFilesDir();
		String localPath = fileDir.getParent()+ File.separator + "wlantest" + File.separator  ;
		
		//----------------------  end -------------------------------------------------
        
        String remotePath = "/";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        remotePath = remotePath + formatter.format(curDate) + "/";
        FtpTestManager fm = new FtpTestManager(localPath, remotePath, fileName);
//        fm.setCtx(ctx);
        if (fm.login(ftp.address, ftp.port, ftp.userName, ftp.password)) {
            if (fm.upload() > 0) {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_TASK_DONE;
                msg.sendToTarget();
                fm.logout();
                File file = new File(localPath + fileName);
                if (file.exists()) {
                    file.delete();
                }
                success = true;
            } else {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
                msg.sendToTarget();
            }
        } else {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_LOGIN_FAILED;
            msg.sendToTarget();
        }
        return success;
    } 
    
    
    protected int uplodFiles(final List<String> fileNames, Activity ctx, Handler handler) {
        Message msg = null;
        boolean success = false;
        DBManager db = new DBManager(ctx);
        FTPConfig ftp = db.getFtp2();
        db.release();
        int num = 0;
        if (ftp == null) {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
            msg.sendToTarget();
            return 0;
        }
      //  String localPath = Environment.getExternalStorageDirectory() + "/wlantest/";
      //----------------------  begin ------------------------------------------------- 
        File fileDir = ctx.getFilesDir();
		String localPath = fileDir.getParent()+ File.separator + "wlantest" + File.separator  ;
		
		//----------------------  end -------------------------------------------------
        
        String remotePath = "/";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        remotePath = remotePath + formatter.format(curDate) + "/";
        for(int i=0;i<fileNames.size();i++){
        	String fileName = fileNames.get(i);
        	FtpTestManager fm = new FtpTestManager(localPath, remotePath, fileName);
        	 System.err.println("----------->"+ftp.address+ftp.port+ftp.userName+ftp.userName);
             
        	if (fm.login(ftp.address, ftp.port, ftp.userName, ftp.password)) {
              if (fm.upload() > 0) {
            	  if(i== fileNames.size()-1){
                      msg = handler.obtainMessage();
                      msg.what = MessageWhat.FTP_UPLOAD_TASK_DONE;
                      msg.sendToTarget();
            	  }
                  fm.logout();
                  File file = new File(localPath + fileName);
                  if (file.exists()) {
                      file.delete();
                  }
                  num++;
                  success = true;
              } else { 
	                  msg = handler.obtainMessage();
	                  msg.what = MessageWhat.FTP_UPLOAD_FAILED;
	                  msg.sendToTarget();
	                  break;
              }
          } else {
              msg = handler.obtainMessage();
              msg.what = MessageWhat.FTP_LOGIN_FAILED;
              msg.sendToTarget();
          }
        }
        return num;
    } 
    //上传图片
    protected boolean uploadPic(final String fileName, Activity ctx, Handler handler) {
        Message msg = null;
        boolean success = false;
        DBManager db = new DBManager(ctx);
       
        FTPConfig ftp = db.getFtp2();
        db.release();
        if (ftp == null) {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
            msg.sendToTarget();
            return success;
        }
      //  String localPath = Environment.getExternalStorageDirectory() + "/wlantest/";
      //----------------------  begin ------------------------------------------------- 
        File fileDir = ctx.getFilesDir();
		String localPath = fileDir.getParent()+ File.separator + "wlantest" + File.separator  ;
		
		//----------------------  end -------------------------------------------------
        
        String remotePath = "/";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        remotePath = remotePath + "/UpImages/";
        FtpTestManager fm = new FtpTestManager(localPath, remotePath, fileName);
//        fm.setCtx(ctx);
        if (fm.login(ftp.address, ftp.port, ftp.userName, ftp.password)) {
            if (fm.upload()> -1) {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_TASK_DONE;
                msg.sendToTarget();
                fm.logout();
                File file = new File(localPath + fileName);
                if (file.exists()) {
                    file.delete();
                }
                success = true;
            } else {
                msg = handler.obtainMessage();
                msg.what = MessageWhat.FTP_UPLOAD_FAILED;
                msg.sendToTarget();
            }
        } else {
            msg = handler.obtainMessage();
            msg.what = MessageWhat.FTP_LOGIN_FAILED;
            msg.sendToTarget();
        }
        return success;
    } 
    protected void initTask(final Task task, Activity ctx, int type) {
    	TelManager tm = new TelManager(ctx);
        task.neighborInfos = tm.getNeighborInfos();
        task.testPhone = tm.getPhoneNumber();
        if (type == ConnectivityManager.TYPE_WIFI) {
            task.netType = "WLAN测试";
//            WlanManager wmanager = new WlanManager(ctx);
//            WifiInfo info = wmanager.getCurrentNetwork();
//            task.mac = info.getMacAddress();
//            task.rssi = String.valueOf(info.getRssi());
        }else if (type == ConnectivityManager.TYPE_MOBILE) {
            task.netType = "GSM测试";
//            task.rssi = tm.getStrSignalStrength();
//            System.err.println("========================================="+task.rssi);
        }else if (type == ConnectivityManager.TYPE_MOBILE_MMS){
        	task.netType = "TD测试";
		}
        GPSUtils gpsUtil = new GPSUtils(ctx);
        double longitude = gpsUtil.getLongitude();
        double latitude = gpsUtil.getLatitude();

        Log.d("GPS", "longitude:" + longitude + ";latitude" + latitude);
        // if (longitude != 0 && latitude != 0) {
        GPS gps = task.newGPS();
        gps.Longitute = Double.toString(longitude);
        gps.Latitute = Double.toString(latitude);
        task.gps = gps;

        int lac = tm.getLac();
        int ci = tm.getCI();
        Log.d("Tel", "lac:" + lac + ";ci" + ci);
        task.lac = String.valueOf(lac);
        task.ci = String.valueOf(ci);

        GSM gsm = task.newGSM();
        gsm.netType = tm.getNetworkType();
        gsm.ber = String.valueOf(tm.getBER());
        gsm.ci = String.valueOf(tm.getCI());
        gsm.lac = String.valueOf(tm.getLac());
        gsm.fieldstrength = String.valueOf(tm.getSignalStrength());
        gsm.rssi = task.rssi;
        task.gsm = gsm;

        TD td = task.newTD();
        td.netType = tm.getNetworkType();
        td.ber = String.valueOf(tm.getBER());
        td.ci = String.valueOf(tm.getCI());
        td.lac = String.valueOf(tm.getLac());
        td.fieldstrength = String.valueOf(tm.getSignalStrength());
        //td.rssi = "-1";
        td.rssi = task.rssi;
        task.td = td;
    } 
    //跳转至TD/GSM两网切换
    
    public void showAlertDialog(final Activity ctx,String message) { 
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
    	builder.setTitle("测试提示");   
    	builder.setMessage(message); 
    	builder.setCancelable(false);
 		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
 				try {
// 					ctx.startActivity(new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS));
 					Intent intent = new Intent(Intent.ACTION_MAIN);
 					intent.setClassName("com.android.phone", "com.android.phone.NetworkSetting");
 					ctx.startActivity(intent);
 					dialog.cancel();
				} catch (Exception e) {
					e.printStackTrace();
 					showMessage(ctx, "该手机不支持TD/GSM网络切换");
 				} 
 			}
 		}); 
 		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
        		dialog.cancel();
 			}
 		});
 		wifiListDialog = builder.create();
        wifiListDialog.show();
    }
   
    protected boolean isAccountSaved() {
    	db = new DBManager(ctx);
    	Account account = db.getAccount();
    	ChinaNetAccount cAccount = db.getChinaNetAccount();
    	ChinaUnicomAccount uAccount = db.getUnicomAccount();
    	db.release();
    	if(account == null || cAccount == null || uAccount == null) {
    		showMessage(ctx, "请到系统管理账号配置中输入完整信息");
    		return false;
    	} else if(account.userName == null || account.password == null 
        		|| account.userName.equals("") || account.password.equals("")) {
    		showMessage(ctx, "请到系统管理账号配置中输入完整信息");
    		return false;
        } else if(cAccount.userName == null || cAccount.password == null || cAccount.address == null 
        		|| cAccount.userName.equals("") || cAccount.password.equals("") || cAccount.address.equals("")) {
    		showMessage(ctx, "请到系统管理账号配置中输入完整信息");
        	return false;
        } else if(uAccount.userName == null || uAccount.password == null || uAccount.address == null 
        		|| uAccount.userName.equals("") || uAccount.password.equals("") || uAccount.address.equals("")) {
    		showMessage(ctx, "请到系统管理账号配置中输入完整信息");
        	return false;
        } else {
        	return true;
        }
    }
}
